package com.bacel.nb.product.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bacel.nb.product.core.domain.Device;
import com.bacel.nb.product.core.domain.Syslog;
import com.bacel.nb.product.core.domain.Sysmodule;
import com.bacel.nb.product.core.domain.Sysuser;
import com.bacel.nb.product.core.dto.ListGageModule;
import com.bacel.nb.product.core.dto.sysmoduleDto;
import com.bacel.nb.product.core.service.IDeviceService;
import com.bacel.nb.product.core.service.ILogsService;
import com.bacel.nb.product.core.service.ISysmoduleService;
import com.bacel.nb.product.core.service.impl.DeviceService;
import com.bacel.nb.product.web.enums.CacheKey;
import com.bacel.nb.product.web.template.ViewModel.FreeMarkerView;
import com.bacel.nb.product.web.template.ViewModel.FreeMarkerViewSimple;
import com.bacel.nb.product.web.util.AddToRedis;
import com.bacel.nb.product.web.util.CacheOperation;
import com.bacel.nb.product.web.util.RedisPoolUtils;
import com.bacel.nb.product.web.util.WebUtilify;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Bacel on 2017/4/4.
 */
@RestController
@RequestMapping(value = "/sysmanage/sys", produces = "text/html;charset=UTF-8")
public class SysModuleController {
    private final Logger logger = Logger.getLogger(SysModuleController.class);

    @Autowired
    private ISysmoduleService sysmoduleService;
    @Autowired
    private ILogsService logsService;
    @Autowired
    private IDeviceService deviceService;
    @RequestMapping(value = "/modulelist", method = RequestMethod.GET)
    public final ModelAndView modulelist(final HttpSession session, final HttpServletRequest request)
            throws Exception {
        String path = request.getContextPath();
        String menulist = WebUtilify.BuildMenuinfo(path, sysmoduleService);
        // 显示首页
        ModelAndView mav = new FreeMarkerView("sys/sysmodulelist", "模块列表", path, menulist, session);
        return mav;
    }

    @RequestMapping(value = "/moduletree", method = RequestMethod.GET)
    public final ModelAndView moduletree(final HttpSession session)
            throws Exception {
        // 显示首页
        FreeMarkerViewSimple mav = new FreeMarkerViewSimple("sys/moduletree", "模块列表树型");
        return mav;
    }

    @RequestMapping(value = "/resetcache", method = RequestMethod.POST)
    public String resetcache(final HttpSession session)
            throws Exception {
        // 显示首页
        CacheOperation co = CacheOperation.getInstance();
        co.removeCacheData(CacheKey.sysmodule.toString());
        return WebUtilify.ReturnJsoninfo("");
    }

    @RequestMapping(value = "/getmodule", method = RequestMethod.GET)
    public String getmodule(final HttpServletRequest request)
            throws Exception {
        Integer id = Integer.parseInt(request.getParameter("id"));
        Sysmodule module = this.sysmoduleService.get(id);
        if (module != null)
            return JSON.toJSONString(module);
        return "";
    }

    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public String del(final HttpServletRequest request) {
        String ret = "";
        String errstr = "";
        try {
            Integer delid = Integer.parseInt(request.getParameter("id"));
            if (delid > 0)
                this.sysmoduleService.deleteByIdT(delid);
            else {
                errstr = "传递参数有误";
            }
            Syslog log = new Syslog();
            log.setTitle("删除模块信息");
            log.setContent(delid.toString());
            log.setCreatedate(new Timestamp(System.currentTimeMillis()));
            WebUtilify.WriteLog(log, logsService);
        } catch (Exception ex) {
            //logger.error(ex,"editChannel","更新渠道错误","");
        }
        ret = WebUtilify.ReturnJsoninfo(errstr);
        return ret;
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String editsysmodule(@RequestBody Sysmodule module, final HttpServletRequest request) {
        String ret = "";
        Map<String, Object> info = new HashMap<>();
        info.put("Message", "ok");
        info.put("Content", "操作成功");

        if (module != null && module.getName() != null && module.getLinkurl() != null) {

            if (module.getCreatedate() == null) {
                module.setCreatedate(new Timestamp(System.currentTimeMillis()));
            }
            if (module.getId() != null && module.getId() > 0) {
                this.sysmoduleService.updateT(module);
            } else {
                int insertid = (int) this.sysmoduleService.insertT(module);
                module.setId(insertid);
            }
            Syslog log = new Syslog();
            log.setTitle("修改模块信息");
            log.setContent(JSON.toJSONString(module));
            log.setCreatedate(new Timestamp(System.currentTimeMillis()));
            WebUtilify.WriteLog(log, logsService);
        }
        ret = JSON.toJSONString(info);
        return ret;
    }

    @RequestMapping(value = "/moduledata", method = RequestMethod.GET)
    public String moduledata(final HttpServletRequest request)
            throws Exception {
        String ret = "";
        int pagesize = WebUtilify.parseInt(request.getParameter("rows"), 15);
        int pageindex = WebUtilify.parseInt(request.getParameter("page"), 1);
        int parentid = WebUtilify.parseInt(request.getParameter("parentid"), -1);
        String name = request.getParameter("name");

        ListGageModule<Sysmodule> datamodule = new ListGageModule<>();
        datamodule.setPagesize(pagesize);
        datamodule.setPageindex(pageindex);
        Sysmodule sysmodule = new Sysmodule();
        if (name != null && !name.equals("")) {
            sysmodule.setName(name);
        }
        if (parentid != -1) {
            Sysmodule parent = new Sysmodule();
            parent.setId(parentid);
            sysmodule.setSysmoduleByParentid(parent);
        }
        sysmoduleService.getPageByExampleLike(sysmodule, datamodule);
        Map<String, Object> info = new HashMap<>();
        for (Sysmodule sysmodule1:datamodule.getList()){
            if (sysmodule1.getSysmoduleByParentid()==null){
                Sysmodule sm = new Sysmodule();
                sm.setName("");
                sysmodule1.setSysmoduleByParentid(sm);
            }
        }
        info.put("records", datamodule.getTotalcount());
        info.put("total", datamodule.getPagecount());
        info.put("rows", datamodule.getList());
        try {
            ret = JSON.toJSONString(info, SerializerFeature.DisableCircularReferenceDetect);// JSONArray.toJSONString(datamodule);
        } catch (Exception ex) {
            System.out.println("moduledata:" + ex.toString());
        }
        return ret;
    }

    @RequestMapping(value = "/moduletreedata", method = RequestMethod.GET)
    public String moduletreedata(final HttpSession session)
            throws Exception {
        ListGageModule datamodule = WebUtilify.GetDataModuleAll(sysmoduleService);
        List<sysmoduleDto> list = mouduleEntityToDto(datamodule.getList());
        String ret = BuildChildren(list, "0", 1);
        if (ret.length() > 1)
            ret = "[" + ret.substring(0, ret.length() - 1) + "]";
        return ret;
    }

    //获取用户菜单
    @RequestMapping(value = "/getusermenudata", method = RequestMethod.GET)
    public String getusermenudata(final HttpSession session, final HttpServletRequest request)
            throws Exception {
        String ret;
        Sysuser user = WebUtilify.LoginUserinfo(request);
        List<Sysmodule> sysmodules = sysmoduleService.getusermenudata(user);
        List<sysmoduleDto> list = mouduleEntityToDto(sysmodules);
        ret = BuildChildren(list, "0", 1);
        if (ret.length() > 1)
            ret = "[" + ret.substring(0, ret.length() - 1) + "]";
        return ret;
    }

    //获取用户菜单
    @RequestMapping(value = "/editsysconfig", method = RequestMethod.POST)
    public String editsysconfig(final HttpSession session, final HttpServletRequest request)
            throws Exception {
        List<Device> list = deviceService.getList();
        AddToRedis.addToRedis(list);
        Map<String, Object> info = new HashMap<>();
        info.put("Message", "ok");
        info.put("Content", "操作成功");
        return JSON.toJSONString(info);

    }


    @RequestMapping(value = "/moduleselectdata", method = RequestMethod.GET)
    public String moduleselectdata(final HttpSession session, final HttpServletRequest request)
            throws Exception {
        int parentid = WebUtilify.parseInt(request.getParameter("parentid"), 0);
        ListGageModule datamodule = WebUtilify.GetDataModuleAll(sysmoduleService);
        List<sysmoduleDto> list = mouduleEntityToDto(datamodule.getList());
        sysmoduleDto module = new sysmoduleDto();
        module.setId(parentid);
        module = WebUtilify.setChildren(list, module);
        module.setName("顶级");
        List<sysmoduleDto> relist = WebUtilify.getListChildren(module, 0);

        Map<String, Object> info = new HashMap<>();
        info.put("records", relist.size());
        info.put("rows", relist);

        String ret = "";
        try {
            ret = JSON.toJSONString(info);// JSONArray.toJSONString(datamodule);
        } catch (Exception ex) {
            System.out.println("moduledata:" + ex.toString());
            //logger.error("获取渠道列表错误:" + ex.toString());
            //logger.log .(ex,"channelList","获取渠道列表错误","");
        }
        return ret;
    }


    String BuildChildren(List<sysmoduleDto> list, String parentid, int treestate) {
        // "state":"closed",
        String str = "";
        List<sysmoduleDto> modulelist = new ArrayList<>();
        if (parentid == null || parentid.equals("0")) {
            modulelist = WebUtilify.GetModule(list, parentid, 0);
        } else {
            modulelist = WebUtilify.GetModule(list, parentid, 1);
        }
        if (modulelist.size() > 0) {
            int activeed = 0;
            if (parentid == null || parentid.equals("0")) {
                str += "{";
                str += "\"id\":\"0\",";
                str += "\"text\":\"顶级\",";
                str += "\"url\":\"\",";
                str += "\"activeed\":0,";
                str += "\"memo\":\"\",";
                str += "\"thumbnail\":\"\",";
                str += "\"parentid\":\"-1\",";
            } else {
//                if (!nowurl.equals("") && nowurl.indexOf(modulelist.get(0).getLinkurl().toLowerCase()) >= 0 && !modulelist.get(0).getLinkurl().equals(""))
//                    activeed = 1;
                String thumbnail = "";// dv[0]["thumbnail"].ToString();
                str += "{";
                str += "\"id\":\"" + modulelist.get(0).getId().toString() + "\",";
                str += "\"text\":\"" + modulelist.get(0).getName() + "\",";
                str += "\"url\":\"" + modulelist.get(0).getLinkurl() + "\",";
                str += "\"activeed\":" + activeed + ",";
                str += "\"memo\":\"\",";
                //str += "\"thumbnail\":\"" + WebUtility.JsonMicrosoftescape(thumbnail) + "\",";
                str += "\"parentid\":\"" + modulelist.get(0).getParentid().toString() + "\",";
            }
            List<sysmoduleDto> modulelist_children = new ArrayList<>();
            modulelist_children = WebUtilify.GetModule(list, parentid, 0);
            if (modulelist_children != null && modulelist_children.size() > 0) {
                str += "\"haschildren\":\"1\",";
                if (treestate != 1 && parentid != "0")
                    str += "\"state\":\"closed\",";

                str += "\"children\":[";
                for (int j = 0; j < modulelist_children.size(); j++) {
                    //str += "{" + brs;
                    //str += "\"id\":\"" + dvchildren[j]["id"].ToString() + "\"," + brs;
                    //str += "\"text\":\"" + dvchildren[j]["name"].ToString() + "\"" + brs;
                    str += BuildChildren(list, modulelist_children.get(j).getId().toString(), treestate);
                    //str += "},";
                }
                str = str.substring(0, str.length() - 1);
                str += "]";
            } else {
                str += "\"haschildren\":\"0\"";
                //str = str.Substring(0, str.Length - 1);
            }
            str += "},";
        }
        return str;
    }

    @RequestMapping(value = "/sysconfiglist", method = RequestMethod.GET)
    public final ModelAndView sysconfiglist(final HttpSession session, final HttpServletRequest request)
            throws Exception {
        String ports = String.valueOf(request.getServerPort());
        if (!ports.equals("80")) {
            ports = ":" + ports;
        }
        String basePath = request.getScheme() + "://" + request.getServerName() + ports;
        // 显示首页
        ModelAndView mav = new FreeMarkerView("sys/sysconfiglist", "系统配置", "", basePath + "/sysmanage/sys/sysconfiglist", session);
        // 显示首页
        //ModelAndView mav = new FreeMarkerView("device/add", "编辑");
        return mav;
    }


    private List<sysmoduleDto> mouduleEntityToDto(List<Sysmodule> sysmodules) {
        List<sysmoduleDto> list = new ArrayList<>();
        for (Sysmodule sysmodule : sysmodules) {
            sysmoduleDto Dto = new sysmoduleDto();
            Dto.setId(sysmodule.getId());
            Dto.setName(sysmodule.getName());
            Dto.setLinkurl(sysmodule.getLinkurl());
            if (sysmodule.getSysmoduleByParentid() != null) {
                Dto.setParentid(sysmodule.getSysmoduleByParentid().getId());
            } else {
                Dto.setParentid(0);
            }
            list.add(Dto);
        }
        return list;
    }
}
